package com.zbest.component.dal.sequence;


/**
 * Created by chenzhaoqi on 2015/3/25.
 */
public class ThreadLocalSequence extends DefaultSequence {

    private static long THREADLOCAL_STEP = 50;
    private ThreadLocal<SequenceRange> threadLocalCurrentRange;

    public ThreadLocalSequence(SequenceDao sequenceDao, String seqName) {
        super(sequenceDao, seqName);
        super.nextValue();
        threadLocalCurrentRange = new ThreadLocal<SequenceRange>();
    }

    public long nextValue() throws SequenceException {
        SequenceRange sr = threadLocalCurrentRange.get();
        if (sr == null) {
            long min = nextValue(THREADLOCAL_STEP);
            sr = new SequenceRange(min, min + THREADLOCAL_STEP - 1);
            threadLocalCurrentRange.set(sr);
        }
        long value = sr.getAndAdd(1);
        if (value == -1) {
            long min = nextValue(THREADLOCAL_STEP);
            sr = new SequenceRange(min, min + THREADLOCAL_STEP - 1);
            threadLocalCurrentRange.set(sr);
            value = sr.getAndAdd(1);
        }
        return value;
    }
}
